package cn.pengpeng.day04.index;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;



public class CreateIndexTwo {
	public static class MapTask extends Mapper<LongWritable, Text, Text, Text>{
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			String[] split = value.toString().split("-");
			String word = split[0];
			String replace = split[1].replace("\t", ":");
			context.write(new Text(word), new Text(replace));
		}
	}
	
	public static class ReduceTask extends Reducer<Text, Text, Text, Text>{
		@Override
		protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			StringBuilder sb = new StringBuilder();
			boolean flag = true;
			for (Text text : values) {
				if(flag){
					flag = false;
					sb.append(text.toString());
				}else{
					sb.append("->"+text.toString());
				}
			}
			context.write(key, new Text(sb.toString()));
		}
	}
	
	public static void main(String[] args) throws Exception{
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//设置job的map 和 reduce 是哪一个 提交任务的类
		job.setMapperClass(MapTask.class);
		job.setReducerClass(ReduceTask.class);
		job.setJarByClass(CreateIndexTwo.class);
		
		//设置输出的类型
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		job.setNumReduceTasks(2);
		
		
		//设置输入目录和输出目录
		FileInputFormat.addInputPath(job, new Path("D:/out/index1"));
		FileOutputFormat.setOutputPath(job, new Path("d:/out/index2"));
		
		
		File file = new File("d:/out/index2");
		if(file.exists()){
			FileUtils.deleteDirectory(file);
		}
		
		//提交任务并等待任务结束，能够打印日志
		boolean waitForCompletion = job.waitForCompletion(true);
		System.out.println(waitForCompletion?"程序正常退出":"程序有问题了");	
	}	

}
